(function () {
  var stateMap, fetchReplyList, renderReplyList;
  var replyWrap = document.querySelector('.reply-wrap');

  stateMap = {
    allPage: 1,
    page: 1,
    isFetch: false,
    hasMore: true
  };

  //获取申请记录
  fetchReplyList = function () {
    $.ajax({
      url: util.hostUrl + '/v1/loanRecord/loanRecordList.html',
      type: 'post',
      data: {
        header: JSON.stringify({
          reqKey: util.reqKey,
          cookie: localStorage.jqyCookie,
          token: localStorage.jqyToken
        }),
        param: JSON.stringify({
          app: util.app,
          userId: localStorage.jqyUserId,
          pag: stateMap.page,
          size: 5
        })
      },
      success: function (res) {
        if (res.result.code == 1) {
          stateMap.allPage = res.response.pags;
          //没有数据
          if (stateMap.allPage == 0) {
            util.fetchNoData(document.body);
          } else {
            renderReplyList(res.response.dataList);
          }
        } else {
          util.toast('Oops,发生错误！');
        }
        util.removePageLoading();
        util.removeFetchLoading();
      },
      error: function () {
        util.toast('Oops,网络有问题！');
        stateMap.isFetch = false;
        util.removePageLoading();
        util.removeFetchLoading();
      }
    });
  };

  //渲染申请记录
  renderReplyList = function (arr) {
    if (stateMap.allPage == stateMap.page) {
      stateMap.hasMore = false;
    }

    arr.forEach(function (val) {
      var list = document.createElement('div');
      list.className = 'reply-list';
      list.innerHTML = String() +
        '<a href="./proDetail.html?id='+ val.productId +'">'+
          '<img src="'+ val.logo +'" alt="pro-logo">'+
          '<div class="reply-info">'+
            '<p class="reply-name">'+ val.name +'</p>'+
            '<p class="reply-time">最近申请时间：'+ val.time +'</p>'+
          '</div>'+
        '</a>';

      replyWrap.appendChild(list);
    });

    stateMap.isFetch = false;
  };

  //滚动加载更多
  var hgt = window.innerHeight + 50;
  window.onscroll = function () {
    if (!stateMap.isFetch && stateMap.hasMore
      && replyWrap.getBoundingClientRect().bottom <= hgt) {
      stateMap.isFetch = true;
      stateMap.page++;

      fetchReplyList();
      util.addPageLoading(replyWrap.parentNode);
    }
  };

  util.addFetchLoading();
  fetchReplyList();
}());